package com.xiongtian.springframework.beans.factory.support;

import com.xiongtian.springframework.beans.factory.config.BeanDefinition;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

/**
 * @Author: xiongtian
 * @CreateTime: 2025-03-26  10:02
 * @Version: 1.0
 * @Description: cglib子类创建策略
 */

public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {

    /**
     * 实例化
     *
     * @param beanDefinition Bean定义
     * @param beanName       Bean名称
     * @param constructor    构造器
     * @param args           构造器参数
     * @return 实例化对象
     */
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor constructor, Object[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });
        if (null == constructor) {
            return enhancer.create();
        }
        return enhancer.create(constructor.getParameterTypes(), args);
    }
}
